package com.htht.smartschool.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.htht.smartschool.common.dao.BaseDao;
import com.htht.smartschool.util.config.SystemConfig;


public abstract class ExportServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8319373861953691031L;
	public static String userkeyParam = "key";
	public static String nologinMsg = "没有权限，用户未登陆！";
	private BaseDao baseDao = new BaseDao();

	private Map paramsMap;
	private Result result = new Result();

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			SystemConfig.log.log("call servlet:" + request.getRemoteHost()
					+ "/" + request.getRequestURL());
			boolean isMustLogin = false;
			if (initParames(request, response, isMustLogin)
					&& getResult().getResult() == 1) {
				DataContainer obj = new DataContainer();
				boolean flag = processData(obj);
				if (flag) {
					getResult().setOK(obj.getData());
				} else {
					getResult().setError(obj.getData().toString());
				}
			}
		} catch (Exception e) {
			SystemConfig.log.log(e.getMessage());
			getResult().setError(e.getMessage());
		}
		outputResult(request, response);
	}

	/**
	 * 如果需要检查用户权限，用户重写此方法即可 已经包含错误处理，除非必要，可以不用Try Catch 捕捉错误 返回true将需要的数据存到obj即可
	 * 返回False 错误信息存到obj
	 * 
	 * @param obj
	 * @return
	 */
	public abstract boolean processData(DataContainer obj);

	/**
	 * 输出结果
	 * 
	 * @param request
	 * @param response
	 */
	public void outputResult(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			initOutput(request, response);
			writeJSON(request, response);
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void writeJSON(HttpServletRequest request,
			HttpServletResponse response) {
		out.print(result.toJSON());
	}

	PrintWriter out = null;

	public void initOutput(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			out = response.getWriter();
		} catch (Exception e) {
			// TODO: handle exception
			SystemConfig.log.log(e.getMessage());
			result.setResult(0);
			result.setError(e.getMessage());
		}
	}

	public void endOutput(HttpServletRequest request,
			HttpServletResponse response) {
		out.flush();
		out.close();
	}

	/**
	 * 获取所有的参数信息
	 */
	public boolean initParames(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		boolean flag = true;
		try {
			paramsMap = request.getParameterMap();
			String key = getParam(userkeyParam);
			if (!checkUser(key)) {
				flag = false;
				result.setResult(0);
				result.setError(nologinMsg);
			}
		} catch (Exception e) {
			flag = false;
			result.setResult(0);
			result.setError(e.getMessage());
			SystemConfig.log.log(e.getMessage());
		}
		return flag;
	}

	private HttpSession _Session;
	HttpServletRequest _request;

	public boolean initParames(HttpServletRequest request,
			HttpServletResponse response, boolean ischeckuser)
			throws ServletException, IOException {
		boolean flag = true;
		result.setResult(1);
		try {
			_Session = request.getSession();
			this.response = response;
			this._request = request;
			paramsMap = request.getParameterMap();
			String key = getParam(userkeyParam);
			if (ischeckuser) {
				if (!checkUser(key)) {
					flag = false;
					result.setResult(0);
					result.setError(nologinMsg);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			flag = false;
			result.setResult(0);
			result.setError(e.getMessage());
			SystemConfig.log.log(e.getMessage());
		}

		return flag;
	}

	HttpServletResponse response;

	public HttpServletResponse getResponse() {
		return this.response;
	}

	public HttpServletRequest getRequest() {
		return this._request;
	}

	public HttpSession getSession() {
		return _Session;
	}

	/**
	 * 获取url中对应的参数
	 * 
	 * @param name
	 * @return
	 */
	public String getParam(String name) {
		String value = "";
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				try {
					String[] arr = (String[]) obj;
					String string = arr[0];
					if (string.length() > 0) {
						// System.out.println("direct value is :"+string);
						String scode = "ISO-8859-1";
						String ecode = "UTF-8";
						// scode="UTF-8";

						// System.out.println("test  value is :"+new
						// String(string.getBytes(ecode),scode));
						value = new String(string.getBytes(scode), ecode);
						// System.out.println("decode value is :"+value);
						// SystemConfig.log.log("param:" + name+":"+value );
					}

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return value;
	}

	public int getIntParam(String name) {
		int value = 0;
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				value = Integer.parseInt(((String[]) (obj))[0]);
			}
		}
		return value;
	}

	public long getLongParam(String name) {
		long value = 0;
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				value = Long.parseLong(((String[]) (obj))[0]);
			}
		}
		return value;
	}

	public float getFloatParam(String name) {
		float value = 0;
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				value = Float.parseFloat(((String[]) (obj))[0]);
			}
		}
		return value;
	}

	public Double getDoubleParam(String name) {
		Double value = 0.0;
		if (name != null && paramsMap != null) {
			Object obj = paramsMap.get(name);
			if (obj != null) {
				value = Double.parseDouble(((String[]) (obj))[0]);
			}
		}
		return value;
	}

	String usercode = "";

	public String getUsercode() {
		return usercode;
	}

	public void setUsercode(String usercode) {
		this.usercode = usercode;
	}

	/**
	 * 检查用户是否有效
	 * 
	 * @param key
	 * @return
	 */
	public boolean checkUser(String key) {
		// todo:
		boolean flag = false;
		// flag=true; //todo check user
		String hql = String.format("from User where %1$s='%2$s' ", "userkey",
				key);
		// User u = (User) baseDao.getQueryFirst(hql);
		// if (u != null) {
		// flag = true;
		// usercode = u.getUsercode();
		// }
		return flag;
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
